import { defineStore } from 'pinia';
import { ref, watch } from 'vue';

export const useElderlyStore = defineStore('elderly', () => {
  // 用于存储老人信息
  const elderlyInfo = ref({
    fullName: '',
    dateOfBirth: '',
    healthStatusText: '',
    bed: { roomNumber: '', bedNumber: '' },
    emergencyContactName: '',
    emergencyContactPhone: '',
    checkInStatus: '未入住',
    bedId: '999999',
  });

  // 从 localStorage 中恢复数据
  const loadElderlyInfo = () => {
    const storedData = localStorage.getItem('elderlyInfo');
    if (storedData) {
      elderlyInfo.value = JSON.parse(storedData);
    }
  };

  // 保存数据到 localStorage
  const saveElderlyInfo = () => {
    localStorage.setItem('elderlyInfo', JSON.stringify(elderlyInfo.value));
  };

  // 设置老人信息
  const setElderlyInfo = (info) => {
    elderlyInfo.value = info;
    saveElderlyInfo();  // 设置后保存到 localStorage
  };

  // 在页面加载时加载老人信息
  loadElderlyInfo();

  // 监听 `elderlyInfo` 变化并同步到 localStorage
  watch(elderlyInfo, saveElderlyInfo, { deep: true });

  return {
    elderlyInfo,
    setElderlyInfo,
  };
});
